import type { Html2CanvasOptions } from '~/typings/html2canvas'
import html2Canvas from '~/typings/html2canvas'

const downloadUtil = {
    /**
     * 下载图片
     *
     * @param {string} url 图片资源路径
     * @param {string} name 图片下载名称 (不传则当前时间戳)
     */
    image(url: string, name?: string): void {
        // 创建一个img标签
        const image: HTMLImageElement = new Image()
        // 解决跨域 Canvas 污染问题
        image.setAttribute('crossOrigin', 'anonymous')
        image.onload = function () {
            const canvas: HTMLCanvasElement = document.createElement('canvas')
            canvas.width = image.width
            canvas.height = image.height
            const context: CanvasRenderingContext2D = canvas.getContext(
                '2d'
            ) as CanvasRenderingContext2D
            context.drawImage(image, 0, 0, image.width, image.height)
            const url = canvas.toDataURL('image/png')
            // 生成一个a元素
            const a: HTMLAnchorElement = document.createElement('a')
            // 创建一个单击事件
            const event: MouseEvent = new MouseEvent('click')
            // 将a的download属性设置为我们想要下载的图片名称，若name不存在则使用‘当前时间戳’作为默认名称
            a.download = name || new Date().getTime() + ''
            // 将生成的URL设置为a.href属性
            a.href = url
            // 触发a的单击事件
            a.dispatchEvent(event)
        }
        image.src = url
    },

    /**
     * HTML转图片
     *
     * @param el
     * @param params
     * @param canvasOptions
     */
    async html2Image(
        el: HTMLElement,
        params?: {
            type?: 'png' | 'jpeg'
            name?: string
        },
        canvasOptions?: Html2CanvasOptions
    ): Promise<void> {
        try {
            const { type = 'png', name = 'file' } = params || {}
            const canvas: HTMLCanvasElement = await html2Canvas(el, {
                useCORS: true,
                backgroundColor: 'transparent',
                ...canvasOptions
            })
            const dataURL: string = canvas.toDataURL(`image/${type}`)
            downloadUtil.file(dataURL, name)
        } catch (error: any) {
            feedback.msgError('下载失败，请重试')
            throw new Error(error)
        }
    },

    /**
     * 下载文件
     *
     * @param url
     * @param name
     */
    file(url: string, name: string): void {
        const aTag: HTMLAnchorElement = document.createElement('a')
        document.body.appendChild(aTag)
        aTag.href = url
        aTag.download = name
        aTag.target = '_blank'
        aTag.click()
        aTag.remove()
    }
}

export default downloadUtil
